<template>
  <div class="createBox">
    <el-row :gutter="17">
      <el-col :span="18">
        <div class="lf">
          <h2>发表新攻略</h2>
          <div class="biaoyu">分享你的个人游记，让更多人看到哦！</div>
          <el-input placeholder="请输入标题" v-model="form.title"></el-input>
          <!-- 富文本框 -->
          <client-only>
            <VueEditor
              class="editorBox"
              v-model="form.content"
              :useCustomImageHandler="true"
              @image-added="imgUpload"
              :editorToolbar="customToolbar"
            />
          </client-only>
          <!-- 选择城市 -->
          <el-row type="flex" align="middle" class="xuanzct">
            <el-col :span="3">选择城市</el-col>
            <el-col :span="8">
              <!-- <el-input placeholder="请搜索游玩城市" :span="4" v-model="city"></el-input> -->
              <el-autocomplete
                v-model="cityname"
                placeholder="请搜索游玩城市"
                :trigger-on-focus="false"
                :highlight-first-item="true"
                :fetch-suggestions="querySearch"
                @select="handleSelect"
              ></el-autocomplete>
            </el-col>
          </el-row>
          <!-- 发布保存 -->
          <div class="fabu">
            <el-button type="primary" size="small" @click="fabu">发布</el-button>
            <span>
              或者
              <i @click="baocun">保存到草稿</i>
            </span>
          </div>
        </div>
      </el-col>
      <el-col :span="6" class="rg">
        <div>
          <h4>草稿箱（{{shaogaoData.length}}）</h4>
        </div>
        <div class="jilu" v-for="(item,index) in shaogaoData" :key="index">
          <div class="tl">{{item.title}}</div>
          <div class="ct">
            <span class="date">{{item.tiem}}</span>
            <!-- 删除图标 -->
            <i class="iconfont el-icon-delete" @click="detchaogao(index)"></i>
            <!-- 编辑图标 -->
            <i class="iconfont el-icon-edit" @click="xuanyan(item,index)"></i>
          </div>
        </div>
      </el-col>
    </el-row>

    <LoginDiaLog :visible.sync="islogin" />
  </div>
</template>

<script>
var moment = require("moment");
import LoginDiaLog from "~/components/LoginDialog";
export default {
  components: {
    LoginDiaLog,
  },

  data() {
    return {
      form: {
        title: "",
        content: "",
        city: "",
      },

      cityname: "",
      newData: [],
      // viex的内容
      shaogaoData: [],
      // 富文本框栏目设置数据
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ header: 1 }, { header: 2 }],
        ["image", "code-block"],
      ],
      // 点击编辑的索引
      delIndex: 0,

      // 是否显示登陆组件
      islogin: false,
    };
  },
  watch: {
    "$store.state.user.userInfo": {
      handler() {
        if (this.$store.state.user.userInfo) {
          this.islogin = false;
        }
      },
    },
  },

  created() {
    setTimeout(() => {
      // 刷新页面时延时加载 才能获取到store的内容
      this.shaogaoData = this.$store.state.wenz.wenZhaData;
    }, 300);
  },
  methods: {
    // 富文本框的设置
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      // 这里是富文本框选择完图片会触发的函数
      // 带有四个参数 file, Editor, cursorLocation, resetUploader
      // file 选中的图片
      // Editor 是当前编辑器实例对象
      // cursorLocation 当前光标所在位置
      // resetUploader 这是上传完图片用来重新初始化上传功能的函数
      // 1. 上传图片
      // 2. 拿到图片地址要放入富文本框当中
      console.log(file);
      let formData = new FormData();
      console.log(formData);
      formData.append("files", file);

      console.log(formData.append);
      this.$axios({
        url: "/upload",
        method: "post",
        // headers: {
        //   Authorization: "Bearer " + this.$store.state.user.userInfo.token,
        // },
        data: formData,
      }).then((res) => {
        console.log(res.data);
        Editor.insertEmbed(
          cursorLocation,
          "image",
          this.$axios.defaults.baseURL + res.data[0].url
        );
        resetUploader();
      });
    },

    // 提示的函数  value 是输入的文字  cd返回数据提示
    querySearch(value, cd) {
      console.log(value);
      this.$axios({
        url: "airs/city",
        params: {
          name: value,
        },
      }).then((res) => {
        console.log(res.data);

        if (res.data.data.length == 0) {
          cd([{ value: "搜索不到此城市" }]);
        } else {
          this.newData = res.data.data.map((el) => {
            return { value: el.name, id: el.id };
          });
          cd(this.newData);
        }
      });
    },
    // 选择提示触发的函数
    handleSelect(item) {
      this.form.city = item.id;
      console.log(this.form.city);
    },
    // 提交按钮
    fabu() {
      console.log("上传的数据", this.form);

      if (!this.form.title) return this.$message.error("标题不能为空");
      if (!this.form.content) return this.$message.error("请输入文章内容");
      if (!this.form.city)
        return this.$message.error("城市不能为空或无法发表此城市文章");

      // 判断是否登陆
      if (!this.$store.state.user.userInfo.token) {
        this.islogin = true;
      } else {
        // 获取下来的数据  要经过处理
        let { id, cityname, tiem, ...form } = { ...this.form };

        this.$axios({
          url: "/posts",
          method: "post",
          data: form,
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token,
          },
        }).then((res) => {
          console.log(res.data);
          this.$message.success(res.data.message);
          // 点击发表清空数据
          this.form = {
            title: "",
            content: "",
            city: "",
          };
          this.cityname = "";

          // 点击发送 删除编辑里的数据
          if (this.delIndex) {
            this.detchaogao(this.delIndex - 1);
          }
          this.delIndex = 0;
        });
      }
    },
    // 保存按钮

    baocun() {
      let tiem = moment().format("YYYY-MM-DD");

      this.form.tiem = tiem;
      this.form.cityname = this.cityname;
      this.$store.commit("wenz/setData", this.form);
      // 点击保存清空数据
      this.form = {
        title: "",
        content: "",
        city: "",
      };
      this.tiem = "";
      this.cityname = "";
      this.delIndex = 0;
      this.$message.success("保存成功");
      // 获取数据渲染
      this.shaogaoData = this.$store.state.wenz.wenZhaData;
      console.log(this.shaogaoData);
    },

    // 点击修改图标（从新渲染数据）
    xuanyan(item, index) {
      this.form = { ...item };
      this.cityname = item.cityname;
      // this.detchaogao(index);
      // 获取点击的索引 加一
      this.delIndex = index + 1;

      console.log(this.delIndex);
    },
    detchaogao(index) {
      this.$store.commit("wenz/delData", index);
    },
  },
};
</script>

<style lang="less" scoped>
.createBox {
  max-width: 1000px;
  min-width: 920px;
  margin: 0 auto;
  padding: 20px 0 0 0;
  .lf {
    h2 {
      font-size: 22px;
      font-weight: 400;
      margin: 0 0 10px 0;
    }
    .biaoyu {
      font-size: 12px;
      color: #999;
      margin: 0 0 10px 0;
    }
    .editorBox {
      margin: 20px 0;
      /deep/.ql-editor {
        height: 400px;
      }
    }
    .xuanzct {
      margin-bottom: 20px;
    }
    .fabu {
      margin-bottom: 20px;
      span {
        margin-left: 10px;
        font-size: 14px;
        i {
          color: orange;
          cursor: pointer;
        }
      }
    }
  }
  .rg {
    border: 1px solid #ccc;
    h4 {
      font-weight: 400;
      color: #666;
      padding: 10px;
      border: 1px solid #ccc;
      border-top: 0;
    }
    .jilu {
      margin-top: 10px;
      .tl {
        font-size: 14px;
      }
      .ct {
        .date {
          font-size: 14px;
          color: #999;
        }
        i {
          float: right;
          margin-left: 5px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>